package com.ruoyi.merchant.service.impl;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.SendSmsUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.merchant.domain.dto.MerchantRankingDTO;
import com.ruoyi.merchant.utils.PinyinUtils;
import com.ruoyi.merchant.utils.RandomNumberGenerator;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import io.seata.spring.annotation.GlobalTransactional;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.merchant.mapper.MerchantMapper;
import com.ruoyi.merchant.domain.Merchant;
import com.ruoyi.merchant.service.IMerchantService;
import org.springframework.transaction.PlatformTransactionManager;

import javax.validation.Valid;
import javax.validation.constraints.Pattern;

/**
 * 商户管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-09
 */
@Service
public class MerchantServiceImpl implements IMerchantService 
{
    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private RedisService redisService;

    /**
     * 查询商户
     * 
     * @param mId 商户管理主键
     * @return 商户管理
     */
    @Override
    public Merchant selectMerchantByMId(Long mId)
    {
        return merchantMapper.selectMerchantByMId(mId);
    }

    /**
     * 查询所有的商户列表
     * 
     * @param merchant 商户管理
     * @return 商户管理
     */
    @Override
    public List<Merchant> selectMerchantList(Merchant merchant)
    {
        return merchantMapper.selectMerchantList(merchant);
    }

    /**
     * 查询未被删除的商户列表
     *
     * @return
     */
    @Override
    public List<Merchant> selectNotDeleteMerchants(Merchant merchant) {
        merchant.setIsDeleted(0L);
        return merchantMapper.selectMerchantList(merchant);
    }

    /**
     * 查询审核已被拒绝的商户列表
     *
     * @return
     */
    @Override
    public List<Merchant> selectRefuseAuditStatus(Merchant merchant) {
        merchant.setAuditStatus(2L);
        return merchantMapper.selectMerchantList(merchant);
    }

    /**
     * 查询已审核的商户管理列表
     *
     * @return 商户管理
     */
    @Override
    public List<Merchant> selectPassedMerchantList(Merchant merchant)
    {
        merchant.setAuditStatus(1L);
        return merchantMapper.selectMerchantList(merchant);
    }

    /**
     * 查询已审核且未被删除的商户列表
     *
     * @return 商户管理集合
     */
    @Override
    public List<Merchant> selectPassedAndNotDelMerchantList(Merchant merchant) {
        merchant.setAuditStatus(1L);
        merchant.setIsDeleted(0L);
        return merchantMapper.selectMerchantList(merchant);
    }

    /**
     * 查询正在营业的商户列表
     *
     * @return
     */
    @Override
    public List<Merchant> selectOpeningMerchantList(Merchant merchant) {
        merchant.setAuditStatus(1L);
        merchant.setIsDeleted(0L);
        merchant.setStatus(1L);
        return merchantMapper.selectMerchantList(merchant);
    }

    /**
     * 新增商户管理
     * 
     * @param merchant 商户管理
     * @return 结果
     */
    @Override
    public int insertMerchant(Merchant merchant)
    {
        return merchantMapper.insertMerchant(merchant);
    }

    /**
     * 商户注册方法实现
     *
     * @param merchant
     * @param verificationCode
     * @return
     */
    @Override
    public AjaxResult registerMerchant(Merchant merchant, int verificationCode) {
        if (verificationCode != 1234) {
            return AjaxResult.error("验证码错误");
        }
        Merchant registerMerchant = new Merchant();
        registerMerchant.setPhone(merchant.getPhone());
        registerMerchant.setIsDeleted(0L);
        List<Merchant> merchants = merchantMapper.selectMerchantList(registerMerchant);
        System.out.println(merchants);
        if (!merchants.isEmpty()) {
            if (merchants.get(0).getAuditStatus() == 0) {
                return AjaxResult.error("账户正在审核中,请勿重复注册!");
            }
            if (merchants.get(0).getAuditStatus() == 1) {
                return AjaxResult.error("该手机号已被注册!");
            }
        }
        int i = merchantMapper.insertMerchant(merchant);
        if (i == 0) {
            return AjaxResult.error("注册失败");
        }
        return AjaxResult.success("注册成功,正在审核中", merchant);
    }

    /**
     * 注册时根据手机号获取验证码方法实现
     *
     * @param phoneNumbers
     * @return
     */
    @Override
    public AjaxResult getVerificationCodeRegister(String[] phoneNumbers) {
        return AjaxResult.success("验证码:", getVerificationCode(phoneNumbers));
    }

    /**
     * 商户登录方法实现
     *
     * @param phoneNumber
     * @return
     */
    @Override
    public AjaxResult loginMerchant(String phoneNumber) {
        System.out.println("phoneNumber:" + phoneNumber);
        Merchant merchant = new Merchant();
        merchant.setPhone(phoneNumber);
        // 登录时要求该商户已通过审核且没有被删除
        List<Merchant> list = selectPassedAndNotDelMerchantList(merchant);
        System.out.println("merchantList:" + list);
        if (list.isEmpty()) {
            return AjaxResult.error("该商户未通过审核或未被注册");
        }
        return AjaxResult.success("登录成功", list.get(0));
    }

    /**
     * 登录时根据手机号获取验证码方法实现
     *
     * @param phoneNumbers
     * @return
     */
    @Override
    public AjaxResult getVerificationCodeLogin(String[] phoneNumbers) {
        return AjaxResult.success("验证码:", getVerificationCode(phoneNumbers));
    }

    /**
     * 获取验证码
     *
     * @param phoneNumbers
     * @return
     */
    @Override
    @GlobalTransactional
    public String getVerificationCode(String[] phoneNumbers) {
        if (phoneNumbers == null) {
            throw new IllegalArgumentException("请输入手机号!");
        }

        for (String phoneNumber : phoneNumbers) {
            if (phoneNumber == null || !phoneNumber.matches("^\\+861[3-9]\\d{9}$")) {
                throw new IllegalArgumentException("请输入+86开头的大陆手机号");
            }
        }

        String msg = RandomNumberGenerator.generateRandomDigits(6);
        SendSmsUtil.sendSms(phoneNumbers, msg);
        for (String phoneNumber : phoneNumbers) {
            String redisKey = "sms:code:" + phoneNumber;
            System.out.println("redisKey:" + redisKey);
            redisService.setCacheObject(redisKey, msg, 30L, TimeUnit.MINUTES);
        }
        return msg;
    }

    /**
     * 注册或登录时获取验证码前的判断
     */
    public int registerOrLoginJudge(String phoneNumber) {
        Merchant merchant = new Merchant();
        merchant.setPhone(phoneNumber);
        List<Merchant> merchants = merchantMapper.selectMerchantList(merchant);
        if (merchants.size() > 1) {
            //
            return 2;
        }
        if (merchants.isEmpty()) {
            // 该手机号未被注册!
            return 0;
        }
        return 1;
    }


    /**
     * 修改商户管理
     * 
     * @param merchant 商户管理
     * @return 结果
     */
    @Override
    public int updateMerchant(Merchant merchant)
    {
        return merchantMapper.updateMerchant(merchant);
    }

    @Override
    @GlobalTransactional
    public int auditAndRegister(Long mId) {
        Merchant merchant = merchantMapper.selectMerchantByMId(mId);
        if (merchant == null || merchant.getIsDeleted() == 1) {
            return 0;
        }
        merchant.setAuditStatus(1L);
        int i = updateMerchant(merchant);
        if (i == 0) {
            return 0;
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserName(PinyinUtils.toPinyin(merchant.getContactName()));
        sysUser.setNickName(merchant.getContactName());
        sysUser.setPhonenumber(merchant.getPhone());

        R<Boolean> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);
        if (R.FAIL == registerResult.getCode())
        {
            throw new ServiceException(registerResult.getMsg());
        }
        // 2. 直接根据用户名查询完整用户信息（包含userId）
        R<SysUser> userResult = remoteUserService.getUserByUserName(sysUser.getUserName(), SecurityConstants.INNER);
        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        SysUser registeredUser = userResult.getData();
        if (registeredUser == null || registeredUser.getUserId() == null) {
            throw new ServiceException("获取注册用户ID失败");
        }
        Long[] longs = { 100L };

        merchant.setuId(registeredUser.getUserId());
        int i1 = updateMerchant(merchant);
        if (i1 == 0) {
            return 0;
        }

        AjaxResult insertAuthRoleResult = remoteUserService.insertAuthRole(registeredUser.getUserId(), longs, SecurityConstants.INNER);
        if (insertAuthRoleResult.isError()) {
            return 0;
        }

        return 1;
    }

    /**
     * 批量删除商户管理
     * 
     * @param mIds 需要删除的商户管理主键
     * @return 结果
     */
    @Override
    public int deleteMerchantByMIds(Long[] mIds)
    {
        return merchantMapper.deleteMerchantByMIds(mIds);
    }

    /**
     * 删除商户管理信息
     * 
     * @param mId 商户管理主键
     * @return 结果
     */
    @Override
    public int deleteMerchantByMId(Long mId)
    {
        return merchantMapper.deleteMerchantByMId(mId);
    }

    /**
     * 查询已通过审核的商户列表并根据评论星级排名
     *
     * @return
     */
    @Override
    public List<MerchantRankingDTO> PassedMerchantsListRanking() {
        System.out.println(merchantMapper.PassedMerchantsListRanking());
        return merchantMapper.PassedMerchantsListRanking();
    }

}
